package com.eclink.asset.hardware.server;


import com.eclink.asset.util.MsgUtils;
import com.ruoyi.common.utils.uuid.UUID;
import io.vertx.core.AbstractVerticle;
import io.vertx.core.net.NetServer;
import io.vertx.core.net.NetServerOptions;
import io.vertx.core.net.NetSocket;
import io.vertx.core.parsetools.RecordParser;
import io.vertx.core.streams.ReadStream;
import lombok.extern.slf4j.Slf4j;

import java.util.HashMap;
import java.util.Map;

/**
 * Created by sweet on 2018/1/2.
 * ---------------------------
 */
@Slf4j
public class TcpServerVerticle extends AbstractVerticle {

    private static final Map<String, NetSocket> SOCKET_MAP = new HashMap<>();
    private static final Map<String, Long> ACTIVE_SOCKET_MAP = new HashMap<>();



    private final String id;

    private final Integer port;

    public TcpServerVerticle(Integer port) {
        super();
        this.id = UUID.fastUUID().toString();
        this.port = port;
        this.vertx.getOrCreateContext();
    }

    @Override
    public void start() throws Exception {
        NetServerOptions options = new NetServerOptions();
        options.setTcpKeepAlive(true);

        NetServer server = vertx.createNetServer(options);

        server.connectHandler(netSocket -> {

            System.out.println("socket 进入连接"+netSocket.hashCode());

            netSocket.handler(RecordParser.newDelimited("\n", h -> {

                System.out.println("do message handler......");
                final String msg = h.toString();
                System.out.println("服务器解包: " + msg);

                final String[] msgSplit = msg.split("\\*");
                final String socketId = msgSplit[0];
                if (socketId==null || socketId.isEmpty()) {
                    return;
                }

                System.out.println("msgBody: " + msg);
                System.out.println("the port " + this.port + " received message : "+ msg);

                if ("PING".equals(msg)) { // 心跳
                    netSocket.write(MsgUtils.joinMsg(socketId, "PING"));
                } else {
                    // 其他信息，这里简单模拟一下，原样返回给客户端
                    netSocket.write(MsgUtils.joinMsg(socketId, msg));
                }
            }));

            netSocket.endHandler(end -> {
                log.info("socket end");
            });

            netSocket.exceptionHandler(ex -> {
                log.error("socket ex : ", ex);
            });

        });

        // 检查心跳
//        vertx.setPeriodic(1000l * 60, t -> {
//            System.out.println("SOCKET MAP");
//            System.out.println(SOCKET_MAP);
//            System.out.println("ACTIVE MAP");
//            System.out.println(ACTIVE_SOCKET_MAP);
//
//            Iterator<Map.Entry<String, Long>> iterator = ACTIVE_SOCKET_MAP.entrySet().iterator();
//            while (iterator.hasNext()) {
//                Map.Entry<String, Long> entry = iterator.next();
//                long time = System.currentTimeMillis() - entry.getValue();
//                if (time > (1000 * 60)) {
//                    LOGGER.debug("SocketId: " + entry.getKey() + ", 被清除");
//                    SOCKET_MAP.remove(entry.getKey()).close();
//                    iterator.remove();
//                }
//            }
//        });


        server.listen(port, res -> {
            if (res.succeeded()) {
                System.out.println("Server start !!!");
                log.debug("Tcp Server Start");
            } else {
                log.error(res.cause().getMessage());

            }
        });

    }
}
